package com.fndsoft.zheshangmeap.ui.adapter;

import java.util.ArrayList;
import java.util.List;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.fndsoft.zheshangmeap.domain.BaseDomain;
import com.fndsoft.zheshangmeap.listener.CommonListener;
import com.fndsoft.zheshangmeap.util.ValueUtil;

/**
 * @author carlos carlosk@163.com
 * @version 创建时间：2012-9-16 下午6:06:54 类说明
 */

public abstract class COBaseAdapter<T> extends BaseAdapter {
	private CommonListener commonListener;
	private List<T> dataList;

	public COBaseAdapter(List<T> dataList) {
		if (ValueUtil.isNotEmpty(dataList)) {
			this.dataList = dataList;
		} else {
			this.dataList = new ArrayList<T>();
		}
	}

	public int getCount() {
		return dataList.size();
	}

	public Object getItem(int position) {
		return dataList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	// 这个方法必须要实现,item
	public abstract View getView(int position, View convertView,
			ViewGroup parent);

	/**
	 * 该方法为了防止dataList引用断掉
	 * 
	 * @author carlos E-mail:carloscyy@gmail.com
	 * @version 创建时间：2011-11-22 上午11:13:38
	 * @param dataList
	 */
	public void notifyDataSetChanged(List<T> dataList) {
		this.dataList = dataList;
		notifyDataSetChanged();
	}

	public List<T> getDataList() {
		return dataList;
	}

	/**
	 * 获取一个数据
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：2012-9-17 下午8:38:50
	 * @param index
	 * @return
	 */
	public T getData(int position) {
		return dataList.get(position);
	}

	public CommonListener getCommonListener() {
		return commonListener;
	}

	public void setCommonLinstener(CommonListener commonListener) {
		this.commonListener = commonListener;
	}

	/**
	 * 把监听器绑定在view上
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：2014年4月7日 下午6:23:20
	 */
	protected void fillLinsenerWithView(View view, final int position) {
		if (null == view) {
			return;
		}
		view.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null != getCommonListener()) {
					getCommonListener().onClickOne(Integer.valueOf(position));
					return;
				}
				Object o = getData(position);
				if (o instanceof BaseDomain) {
					BaseDomain domain = (BaseDomain) o;
					if (null != domain.getCommonLinstener()) {
						domain.getCommonLinstener().onClickOne(domain);
					}
				}
			}
		});

	}

}
